<template>
  <div id="test">
    <!-- 申请空闲主持人 -->
    <div class="host" v-if="crown">
      <img src="../../../static/img/host.png" alt="..." content="获取主持人" @click="freeHost" />
      <p>
        <span>主持人空闲中，可点击获取主持人</span>
      </p>
    </div>
    <!-- 主要绘图 -->
    <canvas class="img" id="img"></canvas>
    <canvas class="data" id="data"></canvas>
    <!-- <img src="../assets/img/视频白板.jpg" alt=""> -->
    <canvas
      class="draw"
      id="draw"
      @mousedown="down($event)"
      @mousemove="move($event)"
      @mouseup="up($event)"
      ref="canvasBox"
    ></canvas>
    <!-- 文字输入框 -->
    <input
      type="text"
      class="ipt"
      v-model="fontText"
      ref="input"
      :style="{ left: iptLeft + 'px', top: iptTop + 'px' }"
      v-show="iptShow"
      @blur="drawFont()"
    />
    <Toolbar v-on:Color="thisColor" v-on:toolbar="thisToolbar"></Toolbar>
    <!-- 底部文件 -->
    <File :host="host" :gxFile="gxFile"></File>
    <!-- <File v-on:Url="imgUrl" :files="files" :host="host" :gxFile="gxFile"></File> -->
    <!-- 聊天窗口和人员信息 -->
    <div class="chat-container" :style="{ right: chatRight + 'px' }">
      <div class="chat-header">
        <div class="tab-btn">
          <p
            class="tab-btn-people"
            :class="{ 'tab-active': isPeople }"
            @click="changeTab('isPeople')"
          >成员列表</p>
          <p class="tab-btn-chat" :class="{ 'tab-active': isChat }" @click="changeTab('isChat')">聊天</p>
        </div>
      </div>
      <div class="chat-content">
        <userList v-show="isPeople" :peopleList="peopleList" :hostFlag="hostFlag">></userList>
        <chat v-show="isChat" ref="ChatChild" :chatInfo="chatInfo"></chat>
      </div>
    </div>
  </div>
</template>
<script>
import drawDesign from "../../service/draw.js";
import Toolbar from './component/Toolbar';
import File from './component/File';
import chat from "./component/chat";
import userList from "./component/userList";
export default {
  components: {
    Toolbar, // 工具模块
    File, // 文件模块
    chat, // 聊天模块
    userList // 用户列表
    // message // 聊天模块
  },
  data() {
    return {
      WssSocket: null, // webSocket对象
      RI: {}, // 存放房间所有信息
      allData: {}, // 存放所有操作数据，包括绘画数据
      host: 0, //  主持人表示 1 为主持人，0 为参会人员 
      iptShow: false, // 文字输入框是否显示
      iptLeft: null, // 判断点下的是左键还是右键
      iptTop: null,
      fontText: null, // 文字文本
      fontx: null, // 文字输入框位置
      fonty: null,
      gxFile: null, // 共享文件对象
      peopleList: null, // 用户列表
      chatRight: 0,
      isPeople: false, //当前我成员列表
      isChat: true,
      chatInfo: null,
      hostFlag: false,
      imgNowData: null,
      crown: false, // 申请主持人的皇冠是否显示
    };
  },
  destroyed() { // 离开路由
    console.log('离开路由，断开WSS：', this.WssSocket)
    this.WssSocket.close() // 断开websocket连接
  },
  mounted() {
    this.initRoomInfo();
    this.initCanvas(); // 获取canvas的 dom 和 上下文 并初始化 宽高
    this.initWebSocket(); // 初始化WebSocket
    window.onresize = () => { // 画布根据屏幕缩放初始化
      this.initCanvas();
      this.initLoading1();
      if (this.RI.fileId) {
        drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
      }
    }
  },
  methods: {
    initRoomInfo() { // 初始化房间的一些数据
      this.RI.roomId = this.$route.query.id; // 当前房间id
      this.RI.userId = window.localStorage.getItem("account"); // 当前用户
      this.RI.userName = window.localStorage.getItem("username");
      this.RI.userImg = window.localStorage.getItem("userimg");
      this.RI.color = '#FF0000'; // 当前画笔初始化颜色
      this.RI.tool = '涂鸦'; // 当前画笔初始化
      this.RI.zoom = 1; // 缩放倍数
      this.RI.pid = 1; // 项目id
      this.RI.tid = 1; // 任务id
      this.RI.LEFT = false; // 判断点下的是左键还是右键
      this.RI.flag = false; // 判断点下绘图
      this.RI.lineWidth = 2; //  当前绘画线条宽度
      this.RI.Roller = false; // 判断能否缩放
    },
    initCanvas() { // 初始化canvas
      this.RI.img = document.getElementById("img"); // 获取到第一层canvas元素
      this.RI.data = document.getElementById("data"); // 获取到第二层canvas元素
      this.RI.draw = document.getElementById("draw"); // 获取到第三层canvas元素

      this.RI.ctxImg = this.RI.img.getContext("2d"); // 获取到第一层canvas元素的上下文
      this.RI.ctxData = this.RI.data.getContext("2d"); // 获取到第二层canvas元素的上下文
      this.RI.ctxDraw = this.RI.draw.getContext("2d"); // 获取到第三层canvas元素的上下文

      this.RI.canvasWidth = this.$refs.canvasBox.clientWidth;
      this.RI.canvasHeight = this.$refs.canvasBox.clientHeight; // 保存一份宽高到drawDesign

      this.RI.img.width = this.RI.canvasWidth;
      this.RI.img.height = this.RI.canvasHeight;
      this.RI.data.width = this.RI.canvasWidth;
      this.RI.data.height = this.RI.canvasHeight;
      this.RI.draw.width = this.RI.canvasWidth;
      this.RI.draw.height = this.RI.canvasHeight; // 设置三个canvas的统一宽高
      document.oncontextmenu = function (e) { return false; } // 禁止整个浏览器的右键默认事件
      this.RI.draw.addEventListener("mousewheel", this.handleScroll); // chrome and ie
      this.RI.draw.addEventListener("DOMMouseScroll", this.handleScroll); // firefox   给canvas添加鼠标滚轮事件
    },
    // canvas加载图片
    initLoading() {
      this.RI.img = new Image();
      this.RI.img.onload = () => { // 图片加载完毕后执行以下方法
        this.RI.imgWidth = this.RI.img.naturalWidth; // 获取图片的原始高宽
        this.RI.imgHeight = this.RI.img.naturalHeight;
        let initImg = drawDesign.initLoadImg(this.RI.canvasWidth, this.RI.canvasHeight, this.RI.imgWidth, this.RI.imgHeight); // 返回图片应该加载的初始位置和结束位置
        this.RI.x = initImg.x;
        this.RI.y = initImg.y;
        this.RI.x1 = initImg.x;
        this.RI.y1 = initImg.y;
        this.RI.endx = initImg.endx;
        this.RI.endy = initImg.endy;
        this.RI.endx1 = initImg.endx;
        this.RI.endy1 = initImg.endy;
        this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 加载背景图之前先清空背景图canvas
        this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy); // 加载背景图
        this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 加载数据之前清空第二层数据canvas
        drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
      }
      this.RI.img.src = this.RI.src; // src = 原图路径
    },
    initLoading1() {
      this.RI.img = new Image();
      this.RI.img.src = this.RI.src; // src = 原图路径
      this.RI.imgWidth = this.RI.img.naturalWidth; // 获取图片的原始高宽
      this.RI.imgHeight = this.RI.img.naturalHeight;
      let initImg = drawDesign.initLoadImg(this.RI.canvasWidth, this.RI.canvasHeight, this.RI.imgWidth, this.RI.imgHeight); // 返回图片应该加载的初始位置和结束位置
      this.RI.x = initImg.x;
      this.RI.y = initImg.y;
      this.RI.x1 = initImg.x
      this.RI.y1 = initImg.y
      this.RI.endx = initImg.endx
      this.RI.endy = initImg.endy
      this.RI.endx1 = initImg.endx
      this.RI.endy1 = initImg.endy
      this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 加载背景图之前先清空背景图canvas
      this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy); // 加载背景图
    },
    async initWebSocket() { //初始化weosocket
      let data = {
        query: {
          id: '=' + this.$route.query.id
        }
      };
      // 获取房间路由
      let res = await this.http.post("api/no_page/xnsjy_rooms", data);
      if (res.ret == 1) {
        let path = res.info.rows[0].client_roomid;
        const wsurl = `wss://www.xnsjy.cn:446/wss${path}`;
        console.log("房间路由path: ", path);
        this.WssSocket = new WebSocket(wsurl);
        console.log("最终连接wssUrl: ", wsurl, this.WssSocket);

        if (this.WssSocket) {
          this.WssSocket.onmessage = this.websocketonmessage;
          this.WssSocket.onopen = this.websocketonopen;
          this.WssSocket.onerror = this.websocketonerror;
          this.WssSocket.onclose = this.websocketclose;
        }
      }
    },
    websocketonopen(e) { //连接建立之后执行send方法发送数据
      let login_wss = {
        type: 'login',
        data: {
          roomId: this.RI.roomId,
          userId: this.RI.userId,
          userName: this.RI.userName,
          userPic: this.RI.userImg
          // obj: obj
        }
      }
      console.log('连接wss成功，登录对象：', login_wss)
      this.websocketsend(login_wss);
    },
    websocketonerror() { // 连接建立失败重连
      console.log("连接失败")
      // this.initWebSocket();
    },
    websocketclose() { // 断开了连接
      console.log("断开连接", this.WssSocket)
      this.initWebSocket();
    },
    websocketonmessage(e) { //数据接收
      console.log(e)
      let data = JSON.parse(e.data);
      console.log('onmessage：', data);
      if (data.type == 'login') { // 登录成功
        let peopleList = data.info; // 房间用户
        let host = data.hostUseid; // 主持人Id
        if (host != 0) { // 有主持人
          for (let i = 0; i < peopleList.length; i++) { // 循环用户
            if (peopleList[i].userId == host) { // 找到用户里的主持人
              peopleList[i].host = 1; // 修改主持人状态
            }
          }
        } else {
          this.crown = true;
        }
        this.peopleList = peopleList;
        if (host == this.RI.userId) { // 主持人是否是自己，是自己的话修改一下自己的主持人状态
          this.host = 1;
        }
        if (data.curFile != 0) {
          this.switchingPic(data.curFile);
        }
        console.log('登录成功，此时我的身份为：', this.host);
        console.log('登录成功，此时用户列表：', this.host);
      } else if (data.type == 'loginout') { // 接收到退出登录的人员信息还有新的主持人信息
        console.log("loginout: ", data)
        this.hostReplace(data.userId, null, true);
        if (data.hostUserid == data.userId) { // 主持人退出了房间
          this.$message({
            type: 'info',
            message: '主持人退出了房间'
          });
          this.crown = true;
        }
      } else if (data.type == 'forward') { // 实时接收的数据
        if (data.data.type == 'move') { // 接收到移动命令
          this.RI.x = data.data.movex + this.RI.x1;
          this.RI.y = data.data.movey + this.RI.y1;
          this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空背景图
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空数据
          drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
          this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy); // 重新加载背景
          this.RI.x1 = this.RI.x;
          this.RI.y1 = this.RI.y;
        } else if (data.data.type == 'Scroll') { // 滚动
          this.RI.zoom = data.data.zoom;
          this.RI.x = data.data.x;
          this.RI.y = data.data.y;
          this.RI.x1 = data.data.x;
          this.RI.y1 = data.data.y;
          this.RI.endx = data.data.endx;
          this.RI.endy = data.data.endy;
          this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
          this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy);
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
          drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
        }
      } else if (data.type == 'drawInfo') {
        if (data.data.type == 'revoke') { // 接收到回撤命令
          this.allData[this.RI.fileId][this.RI.imgIndex].pop();
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空数据
          drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
        } else if (data.data.type == 'clear') { // 接收到清空命令
          this.allData[this.RI.fileId][this.RI.imgIndex] = [];
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
        } else {
          this.allData[this.RI.fileId][this.RI.imgIndex].push(data.data) // 存放数据
        }
        drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
      } else if (data.type == 'chatInfo') {
        let chatMessage = data.data;
        chatMessage.user_name = data.user_name;
        chatMessage.user_img = data.user_img;
        if (data.cur_time) {
          chatMessage.cur_time = data.cur_time;
        } else {
          chatMessage.cur_time = this.getNowFormatDate();
        }
        this.chatInfo = chatMessage;
      } else if (data.type == 'freeHost') { // 收到申请主持人信息

        if (data.code == 1) { // 1表示成功，0表示失败
          this.crown = false; // 空闲主持人皇冠消失
          if (data.userId == this.RI.userId) { // 主持人是否是自己
            this.host = 1;
          }
          for (let i = 0; i < this.peopleList.length; i++) { // 更新用户里面的主持人身份
            if (data.userId == this.peopleList[i].userId) {
              this.peopleList[i].host = 1
            }
          }
          this.$message.success(data.name + '已成为新的主持人');
        } else {
          this.$message({
            type: 'info',
            message: '晚了一步，主持人被抢走了！'
          });
        }
        console.log('我目前的身份：', this.host, this.peopleList)
      } else if (data.type == 'host') { // 收到申请主持人信息

        this.hostFlag = true; // 有人正在申请主持人状态，其他人员不可申请
        if (this.host == 1) { // 判断自己是主持人，不是主持人则不管
          this.$confirm(data.data.userNmae + '申请成为主持人，是否同意', '提示', {
            confirmButtonText: '同意',
            cancelButtonText: '拒绝',
            type: 'info'
          }).then(() => { // 同意申请主持人
            // this.hostFlag = false;
            this.host = 0;
            // this.hostReplace(null, data.data.userId, false);
            let obj = {
              type: 'replace',
              data: {
                new: {
                  userId: data.data.userId,
                  userName: data.data.userNmae,
                },
                old: {
                  userId: this.RI.userId,
                  userName: this.RI.userName,
                }
              }
            }
            this.websocketsend(obj);
          }).catch(() => {
            this.hostFlag = false;
            let obj = {
              type: 'refuse',
              data: {
                userId: data.data.userId,
                userName: data.data.userNmae,
              },
            }
            this.websocketsend(obj)
            this.$message({
              type: 'info',
              message: '已拒绝'
            });
          });
        }

      } else if (data.type == 'replace') { // 同意申请

        this.hostFlag = false;
        this.$message.success(data.data.new.userName + '已成为新的主持人');
        this.hostReplace(null, data.data.new.userId, false);

      } else if (data.type == 'refuse') { // 拒绝申请
        this.hostFlag = false;
        console.log(data, data.data.userId, this.RI.userId)

        if (data.data.userId == this.RI.userId) { // 判断是不是自己被拒绝
          this.$message.info('您的申请，已被拒绝');
        }

      } else if (data.type == 'selectFile') { // 接收到房主切换文件消息
        this.switchingPic(data.data);
      }
    },
    websocketsend(Data) { // 数据发送
      console.log("WssSend:", Data);
      this.WssSocket.send(JSON.stringify(Data)); // 这个正常
    },
    hostReplace(oldHostId, newHostId, flag) { // 更换主持人操作函数 flag为true表示主持人退出更换，flag为flase表示会议人员申请更换
      if (flag) { // 有人退出房间，将该人从用户数组移除
        for (let i = 0; i < this.peopleList.length; i++) { // 从用户数组剔除退房人员
          if (this.peopleList[i].userId == oldHostId) {
            this.peopleList.splice(i, 1)
          }
        }
      } else { // 有人申请成功，替换主持人，先将所有人员都改为参会人员
        for (let i = 0; i < this.peopleList.length; i++) { // 从用户数组剔除退房人员
          this.peopleList[i].host = 0
        }
      }
      if (newHostId) {
        if (this.RI.userId == newHostId) { // 判断自己是否为新的主持人
          this.host = 1;
        }
        for (let q = 0; q < this.peopleList.length; q++) { // 从用户数组更改新的主持人
          if (this.peopleList[q].userId == newHostId) {
            this.peopleList[q].host = 1;
          }
        }
      }
    },
    freeHost() {
      let data = {
        type: "freeHost",
        data: {
          name: this.RI.userName
        }
      }
      this.websocketsend(data)
    },
    drawFont() { // 文字框失去焦点绘画文字
      if (this.fontText != null) { // 文字不为空触发以下事件
        let obj = { // 创建文字数据对象
          type: 'drawInfo',
          data: {
            type: "font",
            roomId: this.RI.roomId,
            fileId: this.RI.fileId,
            imgIndex: this.RI.imgIndex,
            data: {
              x: ((this.fontx - this.RI.x) / this.RI.endx).toFixed(3),
              y: ((this.fonty - this.RI.y) / this.RI.endy).toFixed(3),
              text: this.fontText
            },
            attr: {
              size: '15',
              zoom: this.RI.zoom,
              color: this.RI.color
            }
          }
        };
        drawDesign.drawFont(this.RI.ctxData, this.fontx, this.fonty, this.fontText, '15px 宋体', this.RI.color);
        if (this.WssSocket !== null) {
          this.websocketsend(obj);
        }
        this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
        // this.socketEmit('draw-info', obj)
        this.iptShow = false;
        this.fontText = null;
      } else {
        this.iptShow = false;
      }
    },
    down(e) {
      console.log('点下了鼠标', e.button, ' this.host:', this.host)
      if (e.button == 2) { // 点下的右键
        this.RI.LEFT = false
      } else if (e.button == 0) { // 点下的左键
        this.RI.LEFT = true;
        this.RI.arrX = [];
        this.RI.arrY = []; // 初始化点线数组
        if (!this.iptShow || this.fontText == null) {
          this.fontx = e.offsetX;
          this.fonty = e.offsetY;
        }
        if (this.RI.tool == '文字' && this.host == 1) { // 绘画文字
          this.iptShow = true;
          this.iptLeft = this.fontx
          this.iptTop = this.fonty
          setTimeout(() => {
            this.$refs.input.focus();
          }, 500);
        }
      }
      this.RI.downx = e.offsetX;
      this.RI.downy = e.offsetY; // 保存鼠标点下的位置
      if (this.RI.fileId) {
        this.RI.flag = true; // 确认鼠标点下，可以触发移动
      }
    },
    up(e) {
      if (this.RI.flag) {
        this.RI.flag = false; // 确认抬起点下，不能触发移动
        this.RI.x1 = this.RI.x;
        this.RI.y1 = this.RI.y;
        this.RI.movex = e.offsetX - this.RI.downx;
        this.RI.movey = e.offsetY - this.RI.downy;
        let obj = {};
        if (this.RI.LEFT) {
          switch (this.RI.tool) {
            case '涂鸦':
              obj = {
                type: "drawInfo",
                data: { // 鼠标抬起的时候存放点线的绘画数据
                  type: "point",
                  roomId: this.RI.roomId,
                  fileId: this.RI.fileId,
                  imgIndex: this.RI.imgIndex,
                  data: { x: this.RI.arrX, y: this.RI.arrY },
                  attr: { size: this.RI.lineWidth, color: this.RI.color, zoom: this.RI.zoom },
                }
              }
              if (this.WssSocket !== null) {
                this.websocketsend(obj);
              }
              this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
              break;
            case '矩形选框':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空第一层绘板
              drawDesign.drawRect(this.RI.ctxData, this.RI.downx, this.RI.downy, this.RI.movex, this.RI.movey, this.RI.lineWidth, this.RI.color); // 将数据绘画到中间层数据绘板
              obj = {
                type: "drawInfo",
                data: {
                  type: "rect",
                  roomId: this.RI.roomId,
                  fileId: this.RI.fileId,
                  imgIndex: this.RI.imgIndex,
                  data: { x: ((this.RI.downx - this.RI.x) / this.RI.endx).toFixed(3), y: ((this.RI.downy - this.RI.y) / this.RI.endy).toFixed(3) },
                  enddata: { x: ((e.offsetX - this.RI.x) / this.RI.endx).toFixed(3), y: ((e.offsetY - this.RI.y) / this.RI.endy).toFixed(3) },
                  attr: { size: this.RI.lineWidth, color: this.RI.color, zoom: this.RI.zoom },
                },
              };
              if (this.WssSocket !== null) {
                this.websocketsend(obj);
              }
              this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
              break;
            case '线段':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空第一层绘板
              drawDesign.drawPoint(this.RI.ctxData, this.RI.downx, this.RI.downy, e.offsetX, e.offsetY, this.RI.lineWidth, this.RI.color); // 将数据绘画到中间层数据绘板
              obj = {
                type: "drawInfo",
                data: {
                  type: "line",
                  roomId: this.RI.roomId,
                  fileId: this.RI.fileId,
                  imgIndex: this.RI.imgIndex,
                  data: { x: ((this.RI.downx - this.RI.x) / this.RI.endx).toFixed(3), y: ((this.RI.downy - this.RI.y) / this.RI.endy).toFixed(3) },
                  enddata: { x: ((e.offsetX - this.RI.x) / this.RI.endx).toFixed(3), y: ((e.offsetY - this.RI.y) / this.RI.endy).toFixed(3) },
                  attr: { size: this.RI.lineWidth, color: this.RI.color, zoom: this.RI.zoom },
                }
              };
              if (this.WssSocket !== null) {
                this.websocketsend(obj);
              }
              this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
              break;
            case '圆形选框':
              let x = this.RI.movex / 2 + this.RI.downx;
              let y = this.RI.movey / 2 + this.RI.downy;
              let endx = this.RI.movex / 2;
              let endy = this.RI.movey / 2;
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空第一层绘板
              drawDesign.EvenCompEllipse(this.RI.ctxData, x, y, endx, endy, this.RI.lineWidth, this.RI.color); // 将数据绘画到中间层数据绘板
              obj = {
                type: "drawInfo",
                data: {
                  type: "circular",
                  roomId: this.RI.roomId,
                  fileId: this.RI.fileId,
                  imgIndex: this.RI.imgIndex,
                  data: { x: ((x - this.RI.x) / this.RI.endx).toFixed(3), y: ((y - this.RI.y) / this.RI.endy).toFixed(3) },
                  enddata: { x: ((e.offsetX - this.RI.x) / this.RI.endx).toFixed(3), y: ((e.offsetY - this.RI.y) / this.RI.endy).toFixed(3) },
                  attr: { size: this.RI.lineWidth, color: this.RI.color, zoom: this.RI.zoom },
                }
              };
              if (this.WssSocket !== null) {
                this.websocketsend(obj);
              }
              this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
              break;
            case '箭头':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空第一层绘板
              drawDesign.Plot.arrowCoord({ x: this.RI.downx, y: this.RI.downy }, { x: e.offsetX, y: e.offsetY });
              drawDesign.Plot.sideCoord();
              drawDesign.Plot.drawArrow(this.RI.ctxData, this.RI.color); // 将数据绘画到中间层数据绘板
              obj = {
                type: "drawInfo",
                data: {
                  type: "arrow",
                  roomId: this.RI.roomId,
                  fileId: this.RI.fileId,
                  imgIndex: this.RI.imgIndex,
                  data: { x: ((this.RI.downx - this.RI.x) / this.RI.endx).toFixed(3), y: ((this.RI.downy - this.RI.y) / this.RI.endy).toFixed(3) },
                  enddata: { x: ((e.offsetX - this.RI.x) / this.RI.endx).toFixed(3), y: ((e.offsetY - this.RI.y) / this.RI.endy).toFixed(3) },
                  attr: { size: this.RI.lineWidth, color: this.RI.color, zoom: this.RI.zoom },
                }
              };
              if (this.WssSocket !== null) {
                this.websocketsend(obj);
              }
              this.allData[this.RI.fileId][this.RI.imgIndex].push(obj.data) // 存放数据
              break;
            default:
              console.log('其他')
          }
        } else { // 抬起的右键
          // obj = {
          //   type: "forward",
          //   data: {
          //     type: "move",
          //     movex: this.RI.movex,
          //     movey: this.RI.movey,
          //   }
          // };
          // if (this.WssSocket !== null) {
          //   this.websocketsend(obj);
          // }
          drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
        }
      }
    },
    move(e) {
      if (this.RI.flag) { // 判断是否点下了
        this.RI.movex = e.offsetX - this.RI.downx;
        this.RI.movey = e.offsetY - this.RI.downy;
        if (this.RI.LEFT && this.host == 1) { // 点下的是左键
          switch (this.RI.tool) {
            case '涂鸦':
              drawDesign.drawPoint(this.RI.ctxData, this.RI.downx, this.RI.downy, e.offsetX, e.offsetY, this.RI.lineWidth, this.RI.color)
              this.RI.arrX.push(((e.offsetX - this.RI.x) / this.RI.endx));
              this.RI.arrY.push(((e.offsetY - this.RI.y) / this.RI.endy));
              this.RI.downy = e.offsetY;
              this.RI.downx = e.offsetX;
              break;
            case '矩形选框':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
              drawDesign.drawRect(this.RI.ctxDraw, this.RI.downx, this.RI.downy, this.RI.movex, this.RI.movey, this.RI.lineWidth, this.RI.color);
              break;
            case '圆形选框':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
              drawDesign.EvenCompEllipse(this.RI.ctxDraw, this.RI.movex / 2 + this.RI.downx, this.RI.movey / 2 + this.RI.downy, this.RI.movex / 2, this.RI.movey / 2, this.RI.lineWidth, this.RI.color);
              break;
            case '箭头':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
              drawDesign.Plot.arrowCoord({ x: this.RI.downx, y: this.RI.downy }, { x: e.offsetX, y: e.offsetY });
              drawDesign.Plot.sideCoord();
              drawDesign.Plot.drawArrow(this.RI.ctxDraw, this.RI.color);
              break;
            case '线段':
              this.RI.ctxDraw.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
              drawDesign.drawPoint(this.RI.ctxDraw, this.RI.downx, this.RI.downy, e.offsetX, e.offsetY, this.RI.lineWidth, this.RI.color)
              break;
            default:
              console.log('其他')
          }
        } else if (!this.RI.LEFT) { // 点下的是右键
          this.RI.x = this.RI.movex + this.RI.x1;
          this.RI.y = this.RI.movey + this.RI.y1;
          this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空背景图
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空数据
          // drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
          this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy); // 重新加载背景
        }
      } else {
        if (e.offsetX > this.RI.x && e.offsetX < this.RI.endx + this.RI.x && e.offsetY > this.RI.y && e.offsetY < this.RI.endy + this.RI.y) {
          this.RI.Roller = true; // 判断鼠标移动在图片上才能进行缩放操作
        } else {
          this.RI.Roller = false;
        }
      }
    },
    handleScroll(e) {
      if (true) { // if (this.host == '1') {
        var delta = e.wheelDelta || -e.detail;
        if (this.RI.Roller && !this.RI.flag) {
          this.RI.Rollerx = e.offsetX - this.RI.x;
          this.RI.Rollery = e.offsetY - this.RI.y;
          if (delta > 0) {
            // 向上滚动 放大
            if (this.RI.endx1 * this.RI.zoom < this.RI.imgWidth * 10) {
              this.RI.zoom += 0.2;
              this.RI.zoom = parseFloat(this.RI.zoom.toFixed(2));
            }

            this.RI.x = this.RI.x - (this.RI.endx1 * this.RI.zoom - this.RI.endx) * (this.RI.Rollerx / this.RI.endx);
            this.RI.y = this.RI.y - (this.RI.endy1 * this.RI.zoom - this.RI.endy) * (this.RI.Rollery / this.RI.endy);
            this.RI.endx = this.RI.endx1 * this.RI.zoom;
            this.RI.endy = this.RI.endy1 * this.RI.zoom;
            this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
            this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy);
            this.RI.x1 = this.RI.x;
            this.RI.y1 = this.RI.y;
            this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
            drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
            // let obj = {
            //   type: "forward",
            //   data: {
            //     type: "Scroll",
            //     zoom: this.RI.zoom,
            //     x: this.RI.x,
            //     y: this.RI.y,
            //     endx: this.RI.endx,
            //     endy: this.RI.endy,
            //   }
            // };
            // if (this.WssSocket !== null) {
            //   this.websocketsend(obj);
            // }
          } else {
            // 向下滚动 缩小
            this.RI.zoom -= 0.2;
            this.RI.zoom = parseFloat(this.RI.zoom.toFixed(2));
            if (this.RI.zoom < 0.1) {
              this.RI.zoom = 0.1;
            }
            this.RI.x = this.RI.x - (this.RI.endx1 * this.RI.zoom - this.RI.endx) * (this.RI.Rollerx / this.RI.endx);
            this.RI.y = this.RI.y - (this.RI.endy1 * this.RI.zoom - this.RI.endy) * (this.RI.Rollery / this.RI.endy);
            this.RI.endx = this.RI.endx1 * this.RI.zoom;
            this.RI.endy = this.RI.endy1 * this.RI.zoom;
            this.RI.ctxImg.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
            this.RI.ctxImg.drawImage(this.RI.img, 0, 0, this.RI.imgWidth, this.RI.imgHeight, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy);
            this.RI.x1 = this.RI.x;
            this.RI.y1 = this.RI.y;
            this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
            drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
            // let obj = {
            //   type: "forward",
            //   data: {
            //     type: "Scroll",
            //     zoom: this.RI.zoom,
            //     x: this.RI.x,
            //     y: this.RI.y,
            //     endx: this.RI.endx,
            //     endy: this.RI.endy,
            //   }
            // };
            // if (this.WssSocket !== null) {
            //   this.websocketsend(obj);
            // }
          }
        }
      }
    },
    async switchingPic(data) { // 切换图片
      this.RI.fileId = data.fileId;
      this.RI.imgIndex = data.imgIndex;
      this.RI.src = data.url;
      this.RI.zoom = 1;
      if (!this.allData[this.RI.fileId]) { // 没有文件存储对象
        this.allData[this.RI.fileId] = {}; // 创建一个key为文件id的对象
      }
      if (!this.allData[this.RI.fileId][this.RI.imgIndex]) { // 还没有图片数据
        let obj = {
          query: {
            roomid: this.RI.roomId,
            fileid: data.fileId,
            imageid: data.imgIndex,
          }
        };
        // 获取该图的历史数据
        let res = await this.http.post("api/no_page/xnsjy_draw_message", obj);
        res = res.info.rows;
        if (res.length == 0) { // 该图没有历史数据
          // 创建空的图片数据数组
          this.allData[this.RI.fileId][this.RI.imgIndex] = [];
        } else { // 该图有历史数据
          // 将历史数据赋给图片数据
          this.allData[this.RI.fileId][this.RI.imgIndex] = JSON.parse(res[0].content);
        }
      }
      // 重新加载
      this.initLoading();
      // 修改文件模块的状态
      this.gxFile = data;
      console.log('选择的文件：', data)
    },
    thisColor(val) { // 切换画笔的颜色
      this.RI.color = val;
      console.log('当前选择的颜色：', val)
    },
    thisToolbar(data) { // 切换画笔工具
      console.log('当前选择的工具：', data.title)
      if (data.title == '撤销') {
        if (this.host == '1') { // 主持人才能进行该操作
          this.allData[this.RI.fileId][this.RI.imgIndex].pop();
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight); // 清空数据
          drawDesign.drawAllData(this.RI.ctxData, this.RI.x, this.RI.y, this.RI.endx, this.RI.endy, this.RI.zoom, this.allData[this.RI.fileId][this.RI.imgIndex]); // 绘画所有数据
          let obj = {
            type: "drawInfo",
            data: { // 鼠标抬起的时候存放点线的绘画数据
              type: "revoke",
              roomId: this.RI.roomId,
              fileId: this.RI.fileId,
              imgIndex: this.RI.imgIndex,
            }
          }
          if (this.WssSocket !== null) {
            this.websocketsend(obj);
          }

        }
      } else if (data.title == '清空') {
        if (this.host == '1') { // 主持人才能进行该操作

          this.allData[this.RI.fileId][this.RI.imgIndex] = [];
          this.RI.ctxData.clearRect(0, 0, this.RI.canvasWidth, this.RI.canvasHeight);
          let obj = {
            type: "drawInfo",
            data: { // 鼠标抬起的时候存放点线的绘画数据
              type: "clear",
              roomId: this.RI.roomId,
              fileId: this.RI.fileId,
              imgIndex: this.RI.imgIndex,
            }
          }
          if (this.WssSocket !== null) {
            this.websocketsend(obj);
          }
        }
      } else {
        this.RI.tool = data.title;
      }
    },
    // 控制是否显示聊天页面
    changeShowChat(data) {
      if (data == true) {
        this.chatRight = 0
      } else {
        this.chatRight = -350
      }
    },
    // 是否显示聊天列表的tab
    changeTab(str) {
      if (str == "isPeople") {
        this.isPeople = true;
        this.isChat = false;
      } else {
        this.isPeople = false;
        this.isChat = true;
        this.$refs.ChatChild.scrollToBottom()
      }
    },
    getNowFormatDate() { // 获取当前时间
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
      return currentdate;
    }
  }
}
</script>
<style lang="scss" scoped>
#test {
  height: 100%;
  .host {
    position: fixed;
    z-index: 99;
    text-align: center;
    width: 100%;
    height: 100px;
    top: 5%;
    background-color: rgba($color: #000000, $alpha: 0);
  }
  .host img {
    cursor: pointer;
  }
  .host span {
    display: inline-block;
    background-color: #fff;
  }
}
canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  /* z-index: -3 !important; */
}
.img {
  z-index: 3;
  background-color: white;
  /* background-image: url('../../static/img/timg.jpg') */
}
.data {
  z-index: 6;
}
.draw {
  z-index: 9;
}
.ipt {
  position: absolute;
  background: none;
  height: 30px;
  z-index: 19;
  top: 50%;
  left: 50%;
  outline: 0;
  word-wrap: break-word;
  border: 1px dashed #8d270e;
  height: 15px;
  color: #8d270e;
}
.chat-container {
  position: fixed;
  right: 0;
  top: 40px;
  bottom: 75px;
  width: 350px;
  background-color: #fff;
  z-index: 999;
  -webkit-box-shadow: 0 0px 10px #bebebe;
  box-shadow: 0 0px 10px #bebebe;
  transition: right 0.8s;
  -moz-transition: right 0.8s;
  -webkit-transition: right 0.8s;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
  .chat-header {
    padding: 10px 20px;
    .tab-btn {
      -webkit-border-radius: 8px;
      -moz-border-radius: 8px;
      -ms-border-radius: 8px;
      -o-border-radius: 8px;
      border-radius: 8px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      -webkit-user-select: none;
      /*谷歌 /Chrome*/
      -moz-user-select: none;
      /*火狐/Firefox*/
      -ms-user-select: none;
      /*IE 10+*/
      user-select: none;
      .tab-btn-people {
        border-top-left-radius: 8px;
        border-bottom-left-radius: 8px;
      }
      .tab-btn-chat {
        border-top-right-radius: 8px;
        border-bottom-right-radius: 8px;
      }
      .tab-btn-people,
      .tab-btn-chat {
        margin: 0;
        height: 30px;
        line-height: 30px;
        font-size: 10px;
        width: 50%;
        text-align: center;
        border: 1px solid #EE6133;
        cursor: pointer;
      }
      .tab-btn-people {
        border-right: 1px solid #EE6133;
      }
      .tab-active {
        background-color: #EE6133;
        color: #fff;
      }
    }
  }
  .chat-content {
    position: absolute;
    top: 50px;
    bottom: 1px;
    left: 0;
    right: 0;
  }
}
</style>
